// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/substrait/variant_to_vector_converter.h>
#include <pollux/vector/flat_vector.h>

namespace kumo::pollux::substrait {
    namespace {
        template<TypeKind KIND>
        VectorPtr setVectorFromVariantsByKind(
            const std::vector<pollux::variant> &values,
            const TypePtr &type,
            memory::MemoryPool *pool) {
            using T = typename TypeTraits<KIND>::NativeType;

            auto flat_vector =
                    BaseVector::create<FlatVector<T> >(type, values.size(), pool);

            for (vector_size_t i = 0; i < values.size(); i++) {
                if (values[i].isNull()) {
                    flat_vector->set_null(i, true);
                } else {
                    flat_vector->set(i, values[i].value<T>());
                }
            }
            return flat_vector;
        }

        template<>
        VectorPtr setVectorFromVariantsByKind<TypeKind::VARBINARY>(
            const std::vector<pollux::variant> & /* values */,
            const TypePtr & /*type*/,
            memory::MemoryPool * /* pool */) {
            POLLUX_UNSUPPORTED("Return of VARBINARY data is not supported");
        }

        template<>
        VectorPtr setVectorFromVariantsByKind<TypeKind::VARCHAR>(
            const std::vector<pollux::variant> &values,
            const TypePtr &type,
            memory::MemoryPool *pool) {
            auto flat_vector =
                    BaseVector::create<FlatVector<StringView> >(type, values.size(), pool);

            for (vector_size_t i = 0; i < values.size(); i++) {
                if (values[i].isNull()) {
                    flat_vector->set_null(i, true);
                } else {
                    flat_vector->set(i, StringView(values[i].value<TypeKind::VARCHAR>()));
                }
            }
            return flat_vector;
        }
    } // namespace

    VectorPtr setVectorFromVariants(
        const TypePtr &type,
        const std::vector<pollux::variant> &values,
        memory::MemoryPool *pool) {
        return POLLUX_DYNAMIC_SCALAR_TYPE_DISPATCH(
                    setVectorFromVariantsByKind, type->kind(), values, type, pool);
    }
} // namespace kumo::pollux::substrait
